var express = require('express')
var router = express.Router()
var token=require('../utils/token')
var dbhandler=require('../utils/dbhandler')


/* GET users listing. */
router.get('/', function(req, res, next) {
  //验证请求头是否带token(返回true表明token经过验证)
  token.verify(req.headers.token,(result)=>{
    if(result===undefined){
      res.send({
        err:true,
        reason:"token faild"
      })

    }else{
      //默认返回基本信息回去
      var selector={"base.email":result.email}
      var params=req.query
      var needresult={_id:1,base:1}
      Object.keys(params).forEach(param => {
        needresult[param]=1
      });
      dbhandler.find(selector,needresult,(result)=>{
        delete result[0].base.password
        res.send(result)
      })
    }
  })
});


router.post('/signup',(req,res,next)=>{
  var userBase={
    base:{
      email:req.body.email,
      name:req.body.name,
      password:req.body.passwordMD5,

    }
  }
  if([userBase.base.name,userBase.base.email,userBase.base.password].indexOf(undefined||null||'')!=-1){
    res.send("erro signup")
    return
  }
  dbhandler.add(userBase,(result)=>{
    res.send(result)
  })
})

router.post('/login',(req,res,next)=>{
  var signInfo={
    email:req.body.email,
    password:req.body.passwordMD5,
  }
  var selector={"base.email":signInfo.email}
  var needresult={_id:1,base:1}
  dbhandler.find(selector,needresult,(result)=>{
    var resbody={
      success:false,
      result:"",
      display:"",
      token:""
    }
    if(result.length==0){
      resbody.result="no user",
      resbody.display="找不到该用户"
    }else{
      if(signInfo.password===result[0].base.password){
        resbody.success=true
        delete result[0].base.password
        resbody.base=result[0].base
        resbody.display="登陆成功"
        var payload={email:signInfo.email}
        token.generate(payload,1,(result)=>{
          resbody.token=result
        })

      }else{
        resbody.result="erro password",
        resbody.display="密码错误"
      }
    }
    res.send(resbody)
  })
})

router.get('/getUser',(req,res,next)=>{
  
})

module.exports = router;
